package cn.com.adapter;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.com.R;
import cn.com.domain.MsgEntity;
import cn.com.service.MsgService;
/**
 * 消息记录 Adapter
 * @author ChonZY
 */
public class MsgAdapter extends BaseAdapter {
	
	private Context context ;
	private List<MsgEntity> msgs ;
	private LayoutInflater mInflter ; 
	private MsgService service ;
	private File cacheFile ;

	public MsgAdapter (Context context,List<MsgEntity> msgs, File cacheFile ){
		this.context = context;
		this.msgs = msgs;
		this.cacheFile = cacheFile;
		mInflter = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
		service = new MsgService();
	}
	@Override
	public int getCount() {
		return msgs.size();
	}

	@Override
	public Object getItem(int position) {
		return msgs.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = mInflter.inflate(R.layout.lv_msg_item, null);
		ImageView iv_header = (ImageView) view.findViewById(R.id.iv_msg_item_head);
		TextView tv_name = (TextView) view.findViewById(R.id.tv_msg_item_name);
		TextView tv_content = (TextView) view.findViewById(R.id.tv_msg_item_content);
		TextView tv_time = (TextView) view.findViewById(R.id.tv_msg_item_time);
		
		MsgEntity msg = msgs.get(position);
		tv_name.setText(msg.getName());
		tv_content.setText(msg.getContent());
		tv_time.setText(msg.getTime());
		
		asynLoadImageHeader(iv_header,msg.getSrc());
		
		return null;
	}
	private void asynLoadImageHeader(ImageView iv_header, String src) {
		ImageHeaderTask task = new ImageHeaderTask(src,iv_header);
		task.execute();
	}
	/**
	 * 异步加载网络图片
	 * @author ChonZY
	 *
	 */
	private final class ImageHeaderTask extends AsyncTask<String, Integer, Uri>{
		private String path ;
		private ImageView iv_header ;
		public ImageHeaderTask(String path,ImageView iv_header){
			this.path = path ;
			this.iv_header = iv_header;
		}
		@Override
		protected Uri doInBackground(String... params) {
			try {
				return service.getHeadImageUri(path, cacheFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		
		@Override
		protected void onPostExecute(Uri result) {
			super.onPostExecute(result);
			if(iv_header != null && result !=null)
				iv_header.setImageURI(result);
		}
		
		
	}
	

}
